package com.mike.server.engine.socket;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.log4j.Logger;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;

/**
 * Socket引擎配置类,使用Annotation for Xstream alias. 
 * @author <a href="zhaoming23@gmail.com"> Mike </a>
 * @version 1.0
 * 2011-4-4 下午09:59:44
 */
@XStreamAlias ("server")
public class EngineSocketConfig {
	
	private static final Logger LOG = Logger.getLogger(EngineSocketConfig.class);
	public static final int SERVER_PORT = 9123;
	public static final String SERVER_HOST = "192.168.1.125";
	public static final String CONFIG_PATH = "conf/server.xml";
	public static EngineSocketConfig instance = new EngineSocketConfig(SERVER_HOST, SERVER_PORT);
	private static final XStream xStream = new XStream();
	
	@XStreamAlias ("host")
	private String host;
	@XStreamAlias ("port")
	private int port;
	
	private EngineSocketConfig(String host, int port) {
		//Don't allow new it outside...
		this.host = host;
		this.port = port;
	}
	
	public String getHost() {
		return host;
	}

	public int getPort() {
		return port;
	}

	public static EngineSocketConfig getInstance() {
		instance.readConfig();
		return instance;
	}
	
	public void readConfig() {
		try {
			File file = new File(CONFIG_PATH);
			FileInputStream fis = new FileInputStream(file);
			xStream.processAnnotations(EngineSocketConfig.class);
			EngineSocketConfig config = (EngineSocketConfig) xStream.fromXML(fis);
			LOG.debug("EngineSocketConfig HOST:" + config.getHost());
			LOG.debug("EngineSocketConfig PORT:" + config.getPort());
			this.host = config.getHost();
			this.port = config.getPort();
		} catch (FileNotFoundException e) {
			LOG.error(e.getMessage(), e);
		}
	}
	
	@SuppressWarnings("unused")
	private static void makeDefaultConfig() {
		EngineSocketConfig engineSocketConfig = new EngineSocketConfig(SERVER_HOST, SERVER_PORT);
		xStream.processAnnotations(EngineSocketConfig.class);
		try {
			File file = new File(CONFIG_PATH);
			if(file.exists()) file.delete();
			FileOutputStream out = new FileOutputStream(file, true);
			out.write("<!-- This file is make from fk4game system. add by Mike -->\r\n".getBytes());
			xStream.toXML(engineSocketConfig, out);
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
//		makeDefaultConfig();
		EngineSocketConfig.getInstance().readConfig();
	}
}
